﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;

namespace LULSMS
{
    public class SessionManager
    {
        /// <summary>
        /// Cria conection
        /// </summary>
        /// <param name="ip">User Ip</param>
        /// <param name="userName">Username</param>
        /// <param name="password">password</param>
        /// <returns></returns>
        public static string createConnection(string ip, string userName, string password, string appName)
        {
            //caso exista faz update de devolve recurso
            //devolve endereco com quem estava a comunicar
            //Caso não exista cria uma sessão


            //Verifica se existe sessão activa 
            try
            {
                using (LUL_DBEntities entity = new LUL_DBEntities())
                {
                    Membership.ApplicationName = appName;
                    if (Membership.ValidateUser(userName, password))
                    {
                        aspnet_Users u = entity.aspnet_Users.FirstOrDefault(i => (i.UserName.Equals(userName)));
                        try
                        {
                            entity.CreateConnection(u.UserId, ip);
                        }
                        catch
                        {
                        }

                        //UserConnection uc = new UserConnection();
                        //uc.UserID = u.UserId;
                        //uc.IP = ip;
                        //uc.ConnectionID = new Guid();
                        //uc.StartDate = DateTime.Now;
                        //entity.AddToUserConnection(uc);
                        //entity.SaveChanges();
                    }
                    else
                    {
                        return "Authentication Fail";
                    }
                }
                return "Success";
            }
            catch (Exception ex)
            {
                //TODO: Tratar excepções
                if (ex.InnerException != null)
                    return ex.InnerException.Message;
                else
                    return ex.Message;
            }
        }

        public static string updateConnection(string userName, string password, string appName)
        {
            try
            {
                using (LUL_DBEntities entity = new LUL_DBEntities())
                {
                    Membership.ApplicationName = appName;
                    if (Membership.ValidateUser(userName, password))
                    {
                        aspnet_Users u = entity.aspnet_Users.FirstOrDefault(i => (i.UserName.Equals(userName)));
                        //TODO: 1 - Resolver erro dos SP
                        try
                        {
                            entity.UpdateConnectionSP(u.UserId);
                        }
                        catch
                        {
                        }

                        //entity.UpdateConnection(u.UserId,ip);
                        //UserConnection uc = new UserConnection();
                        //uc.UserID = u.UserId;
                        //uc.IP = ip;
                        //uc.ConnectionID = new Guid();
                        //uc.StartDate = DateTime.Now;
                        //entity.AddToUserConnection(uc);
                        //entity.SaveChanges();
                    }
                    else
                    {
                        return "Authentication Fail";
                    }
                }
                return "Success";
            }
            catch (Exception ex)
            {
                //TODO: Tratar excepções
                if (ex.InnerException != null)
                    return ex.InnerException.Message;
                else
                    return ex.Message;
            }
        }

        public static string createSession(string patient, string userName, string password, string appName)
        {

            try
            {
                using (LUL_DBEntities entity = new LUL_DBEntities())
                {
                    //var sel = from us in entity.UserSessions
                    //          from spConec in us.UserConnection1
                    //          where c.EndDate == null;


                    aspnet_Users sp = entity.aspnet_Users.FirstOrDefault(i => (i.UserName.Equals(userName)));
                    aspnet_Users p = entity.aspnet_Users.FirstOrDefault(i => (i.UserName.Equals(patient)));
                    //Só se estiver conectado
                    entity.CreateSessionSP(p.UserId, sp.UserId);

                }
                return "Success";
            }
            catch (Exception ex)
            {
                //TODO: Tratar excepções
                return ex.Message;
            }
        }

        public static string updateSession(string patient, string userName, string password, string appName)
        {
            try
            {
                using (LUL_DBEntities entity = new LUL_DBEntities())
                {

                    aspnet_Users sp = entity.aspnet_Users.FirstOrDefault(i => (i.UserName.Equals(userName)));
                    aspnet_Users p = entity.aspnet_Users.FirstOrDefault(i => (i.UserName.Equals(patient)));
                    //Só se estiver conectado
                    entity.UpdateSessionSP(p.UserId, sp.UserId);

                }
                return "Success";
            }
            catch (Exception ex)
            {
                //TODO: Tratar excepções
                return ex.Message;
            }
        }

        public static LULSMS_Lib.User restoreSession(string user, string userName, string password, string appName)
        {
            try
            {

                using (LUL_DBEntities entity = new LUL_DBEntities())
                {
                    aspnet_Users u = entity.aspnet_Users.FirstOrDefault(i => (i.UserName.Equals(user)));
                    //TODO: 2 - Mudar para assim quando resolver bug
                    //Ver a SP disto está redundante
                    ////Só se estiver conectado
                    // var res = entity.RestoreUserSession(u.UserId);
                    // LULSMS_Lib.User userRes = new LULSMS_Lib.User();
                    // userRes.IP = res.ToString();
                    // userRes.UserName = user;
                    // return userRes;

                    #region semSP
                    var selectIp = from conect in entity.UserConnection
                                   where conect.UserID.Equals(u.UserId) && conect.EndDate == null
                                   orderby conect.StartDate descending
                                   select conect.IP;

                    //string ip = selectIp.FirstOrDefault<string>();
                    List<string> ips = selectIp.ToList<string>();
                    if (ips.Count > 0)
                    {
                        LULSMS_Lib.User uRes = new LULSMS_Lib.User();
                        uRes.IP = ips[0];
                        uRes.UserName = user;
                        if (ips.Count > 1)
                        {
                            //Finaliza todas as activas.
                            //TODO: 5 - Fazer SP que finaliza todas as conecções menos ultima! 
                        }
                        return uRes;

                    }
                    else
                    {
                        throw new Exception("Conection not found");
                    }

                    #endregion

                }
            }
            catch (Exception ex)
            {
                //TODO: Tratar excepções
                return new LULSMS_Lib.User();
            }
        }


    }
}
